#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
财联社电报采集器
"""

import requests
import json
import time
import sys
import os
from datetime import datetime
from core.config import (
    CAILIANPRESS_API_URL, 
    COLLECT_INTERVAL_MINUTES, 
    DISPLAY_LIMIT, 
    REQUEST_TIMEOUT, 
    USER_AGENT,
    WECHAT_ENABLED,
    WECHAT_PUSH_TYPE
)
import logging

# 导入Web配置
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from web.web_config import web_config
try:
    from database.pg_models import PostgresTelegramDatabase, PSYCOPG2_AVAILABLE
except ImportError:
    print("错误: 无法导入PostgresTelegramDatabase类")
    PostgresTelegramDatabase = None
    PSYCOPG2_AVAILABLE = False

# 导入微信推送模块
wechat_notifier = None
try:
    # 首先尝试导入真实的微信推送模块
    # 尝试导入本地微信通知器
    try:
        from core.local_wechat_notifier import local_wechat_notifier as wechat_notifier
        print("使用本地微信客户端推送...")
    except ImportError:
        # 尝试导入其他可能的微信通知器
        try:
            from wechat_notifier import wechat_notifier
            print("使用PushPlus服务推送...")
        except ImportError:
            # 真实模块不可用，尝试使用模拟模块
            try:
                from core.wechat_notifier_mock import wechat_notifier
                print("使用微信推送模拟模块...")
            except ImportError:
                # 检查web_config中是否有微信相关配置
                if web_config.get_full_config().get('wechat_push_enabled', False):
                    print("警告: 微信推送已启用，但微信推送模块不可用。请检查相关依赖或参考配置指南。")
                else:
                    print("微信推送功能当前未启用。")
except Exception as e:
    print(f"警告: 微信推送模块初始化过程中发生错误: {e}")
    wechat_notifier = None


class CailianPressCollector:
    def __init__(self):
        self.api_url = "https://api.98dou.cn/api/hotlist/cls/all"
        # 只使用PostgreSQL数据库
        if PostgresTelegramDatabase and PSYCOPG2_AVAILABLE:
            print("使用PostgreSQL数据库...")
            self.db = PostgresTelegramDatabase()
        else:
            print("错误: PostgreSQL功能不可用（psycopg2模块缺失）")
            print("请安装psycopg2-binary以启用PostgreSQL功能: pip install psycopg2-binary")
            raise ImportError("PostgreSQL功能不可用")
        # 配置日志
        self._setup_logging()
        
    def _setup_logging(self):
        """设置日志"""
        # 确保日志目录存在
        log_dir = "logs"
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
            
        # 配置日志格式
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s %(levelname)s %(message)s',
            handlers=[
                logging.FileHandler(os.path.join(log_dir, "collector.log"), encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
        
    def fetch_telegrams(self):
        """从API获取电报数据"""
        try:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            
            self.logger.info("开始请求财联社电报API")
            response = requests.get(self.api_url, headers=headers, timeout=30)
            response.raise_for_status()
            
            data = response.json()
            self.logger.info(f"API请求成功，状态码: {response.status_code}")
            
            if data.get('success') and 'data' in data:
                self.logger.info(f"获取到 {len(data['data'])} 条电报数据")
                return data['data']
            else:
                error_msg = data.get('msg', '未知错误')
                self.logger.error(f"API返回失败: {error_msg}")
                return []
                
        except requests.exceptions.RequestException as e:
            self.logger.error(f"网络请求错误: {e}")
            return []
        except json.JSONDecodeError as e:
            self.logger.error(f"JSON解析错误: {e}")
            return []
        except Exception as e:
            self.logger.error(f"获取电报数据时出错: {e}")
            return []

    def collect_and_save(self):
        """采集并保存电报数据"""
        start_time = datetime.now()
        self.logger.info("开始采集财联社电报...")
        
        telegrams = self.fetch_telegrams()
        
        if not telegrams:
            self.logger.warning("未获取到电报数据")
            return 0
            
        # 保存到数据库
        inserted_count = self.db.save_telegrams(telegrams)
        
        end_time = datetime.now()
        duration = (end_time - start_time).total_seconds()
        
        self.logger.info(f"成功保存 {inserted_count} 条新电报数据，耗时 {duration:.2f} 秒")
        self.logger.info(f"获取到 {len(telegrams)} 条电报数据")
        self.logger.info(f"数据库中电报总数: {self.db.get_telegram_count()}")
        
        # 微信推送新电报数据
        if wechat_notifier:
            self.logger.info(f"检查是否有未推送的电报数据")
            try:
                # 获取未推送的电报数据（已按最新时间降序排序）
                unpushed_telegrams = self.db.get_unpushed_telegrams(3)  # 最多推送3条
                
                if not unpushed_telegrams:
                    self.logger.info("没有未推送的电报数据")
                    return inserted_count
                
                # 检查Web配置中的微信推送开关
                web_push_enabled = web_config.get_wechat_push_enabled()
                
                if web_push_enabled:
                    self.logger.info(f"Web配置中微信推送已启用，准备推送 {len(unpushed_telegrams)} 条未推送的电报数据到微信群")
                    
                    # 获取Web配置中的目标群组
                    target_groups = web_config.get_target_groups()
                    if not target_groups:
                        self.logger.warning("Web配置中未设置目标推送群，跳过推送")
                        return inserted_count
                    
                    for i, telegram in enumerate(unpushed_telegrams):
                        # 向每个配置的群组推送消息
                        for group_name in target_groups:
                            # 准备推送消息
                            if hasattr(wechat_notifier, 'format_telegram_for_wechat'):
                                message = wechat_notifier.format_telegram_for_wechat(telegram)
                            else:
                                message = f"【财联社电报】\n时间: {telegram.get('time', '')}\n标题: {telegram.get('title', '')}\n内容: {telegram.get('content', '')}"
                            
                            # 发送消息到指定群组
                            if hasattr(wechat_notifier, 'send_message_to_group'):
                                result = wechat_notifier.send_message_to_group(group_name, message)
                                if result is None:
                                    success, msg = False, "发送消息返回空结果"
                                else:
                                    success, msg = result
                            elif hasattr(wechat_notifier, 'send_telegram_to_wechat_group'):
                                # 尝试使用原来的方法，但设置目标群组
                                original_group = wechat_notifier.target_group_name
                                wechat_notifier.target_group_name = group_name
                                result = wechat_notifier.send_telegram_to_wechat_group(telegram)
                                if result is None:
                                    success, msg = False, "发送消息返回空结果"
                                else:
                                    success, msg = result
                                wechat_notifier.target_group_name = original_group  # 恢复原来的群组
                            else:
                                success = False
                                msg = "不支持的推送方法"
                            
                            if success:
                                self.logger.info(f"成功推送第{i+1}条电报数据(时间: {telegram['time']})到微信群 '{group_name}'")
                            else:
                                self.logger.error(f"推送第{i+1}条电报数据到微信群 '{group_name}' 失败: {msg}")
                        
                        # 无论是否推送成功，都标记为已推送（避免重复尝试）
                        self.db.mark_as_pushed(telegram['id_original'])
                else:
                    self.logger.info("Web配置中微信推送未启用，跳过推送")
            except Exception as e:
                self.logger.error(f"微信推送过程中发生错误: {e}")
        
        return inserted_count

    def get_latest_telegrams(self, limit=10):
        """获取最新电报"""
        return self.db.get_latest_telegrams(limit)

    def display_latest_telegrams(self, limit=5):
        """显示最新电报"""
        telegrams = self.get_latest_telegrams(limit)
        
        print(f"\n=== 最新 {limit} 条财联社电报 ===")
        for i, telegram in enumerate(telegrams, 1):
            print(f"\n{i}. {telegram['time']}")
            print(f"   标题: {telegram['title']}")
            print(f"   内容: {telegram['content'][:100]}..." if len(telegram['content']) > 100 else f"   内容: {telegram['content']}")
            print(f"   阅读数: {telegram['reading_num']}")
            print(f"   链接: {telegram['url']}")
            
        print("\n" + "="*50)


# 测试代码
if __name__ == "__main__":
    collector = CailianPressCollector()
    
    # 采集一次数据
    collector.collect_and_save()
    
    # 显示最新电报
    collector.display_latest_telegrams()